import dayjs from 'dayjs'
import Form from '../modules/Form/index.vue'
import { handleTree } from '@/utils/tree'
import { message } from '@/utils/message'
import { ElMessageBox } from 'element-plus'
import { usePublicHooks } from '@/hooks/index'
import { transformI18n } from '@/plugins/i18n'
import { addDialog } from '@/components/ReDialog'
import RoleAPI from '@/api/system/role'
import type { FormQueryData, QueryParams, RoleMenuIdsData } from '@/api/system/role/types'
import type { PaginationProps } from '@pureadmin/table'
import { getKeyList, deviceDetection } from '@pureadmin/utils'
import type { Ref } from 'vue'

export function useRole(treeRef: Ref) {
  const queryParams = reactive<QueryParams>({
    page: 1,
    pageSize: 10,
    name: undefined,
    code: undefined,
    status: undefined
  })

  const curRow = ref()
  const formRef = ref()
  const dataList = ref([])
  const treeIds = ref([])
  const treeData = ref([])
  const isShow = ref(false)
  const loading = ref(true)
  const isLinkage = ref(false)
  const treeSearchValue = ref()
  const switchLoadMap = ref({})
  const isExpandAll = ref(false)
  const isSelectAll = ref(false)
  const { switchStyle } = usePublicHooks()
  const treeProps = {
    value: 'id',
    label: 'title',
    children: 'children'
  }
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  })
  const columns: TableColumnList = [{
    label: '角色编号',
    prop: 'id'
  }, {
    label: '角色名称',
    prop: 'name'
  }, {
    label: '角色标识',
    prop: 'code'
  }, {
    label: '状态',
    cellRenderer: scope => (
      <el-switch
        size={scope.props.size === 'small' ? 'small' : 'default'}
        loading={switchLoadMap.value[scope.index]?.loading}
        v-model={scope.row.status}
        active-value={1}
        inactive-value={0}
        active-text='已启用'
        inactive-text='已停用'
        inline-prompt
        style={switchStyle.value}
        onChange={() => onChange(scope as any)}
      />
    ),
    minWidth: 90
  }, {
    label: '备注',
    prop: 'remark',
    minWidth: 160
  }, {
    label: '创建时间',
    prop: 'createTime',
    minWidth: 160,
    formatter: ({ createTime }) => dayjs(createTime).format('YYYY-MM-DD HH:mm:ss')
  }, {
    label: '操作',
    fixed: 'right',
    width: 210,
    slot: 'operation'
  }]

  // const buttonClass = computed(() => {
  //   return [
  //     "h-[20px]!",
  //     "reset-margin",
  //     "text-gray-500!",
  //     "dark:text-white!",
  //     "dark:hover:text-primary!"
  //   ];
  // })

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${row.name
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message(`已${row.status === 0 ? "停用" : "启用"}${row.name}`, {
            type: "success"
          });
        }, 300);
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  function handleDelete(row: FormQueryData) {
    RoleAPI.delete(row.id).then(() => {
      message(`您删除了角色名称为${row.name}的这条数据`, { type: 'success' })
      onSearch()
    })
  }

  function handleSizeChange(val: number) {
    queryParams.pageSize = val
    pagination.pageSize = val
    onSearch()
  }

  function handleCurrentChange(val: number) {
    queryParams.page = val
    pagination.currentPage = val
    onSearch()
  }

  function handleSelectionChange(val: number) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch() {
    loading.value = true
    const { data } = await RoleAPI.getList(toRaw(queryParams))
    dataList.value = data.list
    pagination.total = data.total
    loading.value = false
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormQueryData) {
    addDialog({
      title: `${title}角色`,
      props: {
        formInline: {
          name: row?.name ?? "",
          code: row?.code ?? "",
          remark: row?.remark ?? ""
        }
      },
      width: "40%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      sureBtnLoading: true,
      closeOnClickModal: false,
      contentRenderer: () => h(Form, { ref: formRef, formInline: null }),
      beforeSure: (done, { options, closeLoading }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormQueryData;
        function chores() {
          message(`您${title}了角色名称为${curData.name}的这条数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate((valid: boolean) => {
          if (valid) {
            if (title === "新增") {
              RoleAPI.create(toRaw(curData)).then(() => {
                chores()
              })
            } else {
              RoleAPI.update(row.id, toRaw(curData)).then(() => {
                chores()
              })
            }
          } else {
            closeLoading()
          }
        })
      }
    })
  }

  /** 菜单权限 */
  async function handleMenu(row?: any) {
    const { id } = row;
    if (id) {
      curRow.value = row;
      isShow.value = true;
      const { data } = await RoleAPI.getRoleMenuIds(id)
      treeRef.value.setCheckedKeys(data)
    } else {
      curRow.value = null;
      isShow.value = false;
    }
  }

  /** 高亮当前权限选中行 */
  function rowStyle({ row: { id } }) {
    return {
      cursor: 'pointer',
      background: id === curRow.value?.id ? 'var(--el-fill-color-light)' : ''
    };
  }

  /** 菜单权限-保存 */
  function handleSave() {
    const { id, name } = curRow.value

    RoleAPI.setRoleMenuIds({
      id,
      ids: treeRef.value?.getCheckedKeys()?.join(',')
    } as RoleMenuIdsData).then(() => {
      message(`角色名称为${name}的菜单权限修改成功`, {
        type: 'success'
      })
    })

  }

  /** 数据权限 可自行开发 */
  // function handleDatabase() {}

  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
    const { data } = await RoleAPI.getRoleMenu()
    treeIds.value = getKeyList(data, 'id')
    treeData.value = handleTree(data)
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  return {
    queryParams,
    isShow,
    curRow,
    loading,
    columns,
    rowStyle,
    dataList,
    treeData,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    // buttonClass,
    onSearch,
    resetForm,
    openDialog,
    handleMenu,
    handleSave,
    handleDelete,
    filterMethod,
    transformI18n,
    onQueryChanged,
    // handleDatabase,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
